﻿using Mapster;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar;

namespace Utils
{
    public class SugarCache : ICacheService
    {
        public void Add<V>(string key, V value)
        {
            CacheHelper.SetCache(key, value);
            Console.WriteLine($"添加缓存键:{key}, value:{value}");
        }

        public void Add<V>(string key, V value, int cacheDurationInSeconds)
        {
            CacheHelper.SetCacheDateTime(key, value, cacheDurationInSeconds);
            Console.WriteLine($"添加缓存键:{key}, value:{value}, 缓存持续时间秒:{cacheDurationInSeconds}");
        }

        public bool ContainsKey<V>(string key)
        {
            Console.WriteLine($"包含缓存key:{key}");
            return CacheHelper.Exists(key);
        }

        public V Get<V>(string key)
        {
            Console.WriteLine($"获取缓存key:{key}");
            return CacheHelper.GetCache(key).Adapt<V>();
        }

        public IEnumerable<string> GetAllKey<V>()
        {
            var result = CacheHelper.GetCacheKeys();
            Console.WriteLine($"获取所有key缓存" + result.ToJson());
            return result;
        }

        public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            if (!CacheHelper.Cache.TryGetValue<V>(cacheKey, out V value))
            {
                value = create();
                Add(cacheKey, value, cacheDurationInSeconds);
            }
            Console.WriteLine($"获取或创建缓存key:{cacheKey}, value:{value}, 缓存持续时间秒:{cacheDurationInSeconds}");
            return value;
        }

        public void Remove<V>(string key)
        {
            CacheHelper.Remove(key);
            Console.WriteLine($"删除缓存key:{key}");
        }
    }
}